package com.linghang.back.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.linghang.back.dto.ArticleDTO;
import com.linghang.back.dto.PageResult;
import com.linghang.back.entity.Article;
import com.linghang.back.repository.ArticleRepository;
import com.linghang.back.service.ArticleService;
import com.linghang.back.util.WechatMpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.Map;

/**
 * 文章服务实现类
 */
@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository articleRepository;

    @Autowired
    private WechatMpUtil wechatMpUtil;
    
    @Autowired
    private ArticleProcessService articleProcessService;

    @Override
    public PageResult<ArticleDTO> getArticleList(Integer pageNum, Integer pageSize, String type) {
        // 页码从0开始
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "publishDate"));
        
        Page<Article> page;
        if (type != null && !type.isEmpty()) {
            page = articleRepository.findByType(type, pageable);
        } else {
            page = articleRepository.findAll(pageable);
        }
        
        return PageResult.fromPage(page, ArticleDTO::fromEntityForList);
    }

    @Override
    public ArticleDTO getArticleDetail(Long id) {
        Article article = articleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("文章不存在"));
        return ArticleDTO.fromEntity(article);
    }

    @Override
    public void syncWechatArticles() throws Exception {
        log.info("开始同步微信公众号文章");
        try {
            // 批量获取素材，每次最多获取20条
            log.info("准备获取公众号文章列表");
            JsonNode response = wechatMpUtil.getBizArticleList("0", "20");
            log.info("获取公众号文章列表成功，开始处理数据");
            
            // 检查是否有错误码
            if (response.has("errcode") && response.get("errcode").asInt() != 0) {
                log.error("获取公众号文章列表错误：errcode={}, errmsg={}", 
                    response.path("errcode").asText(), response.path("errmsg").asText());
                throw new RuntimeException("微信接口返回错误: " + response.path("errmsg").asText());
            }
            
            // 检查正确的JSON路径，freepublish/batchget接口与material接口返回结构不同
            if (response.has("itemCount") && response.has("items") && response.get("items").isArray()) {
                int count = response.get("itemCount").asInt();
                JsonNode articles = response.get("items");
                log.info("获取到{}篇文章，总数量: {}", articles.size(), count);
                
                for (JsonNode article : articles) {
                    try {
                        Map<String, Object> articleData = wechatMpUtil.parseArticle(article);
                        // 使用独立服务处理每篇文章
                        articleProcessService.processArticle(articleData);
                    } catch (Exception e) {
                        log.error("处理文章数据异常", e);
                        // 不影响其他文章的处理
                    }
                }
            } else if (response.has("total_count") && response.has("item") && response.get("item").isArray()) {
                // 兼容另一种可能的响应格式
                int count = response.get("total_count").asInt();
                JsonNode articles = response.get("item");
                log.info("使用备选结构解析，获取到{}篇文章，总数量: {}", articles.size(), count);
                
                for (JsonNode article : articles) {
                    try {
                        Map<String, Object> articleData = wechatMpUtil.parseArticle(article);
                        // 使用独立服务处理每篇文章
                        articleProcessService.processArticle(articleData);
                    } catch (Exception e) {
                        log.error("处理文章数据异常: {}", e.getMessage(), e);
                        // 不影响其他文章的处理
                    }
                }
            } else {
                log.warn("获取文章列表失败，响应结构不符合预期: {}", response.toString());
                throw new RuntimeException("获取文章列表失败，响应结构不符合预期");
            }
            
            log.info("完成同步微信公众号文章");
        } catch (Exception e) {
            log.error("同步微信公众号文章异常", e);
            throw e;
        }
    }

    @Override
    public PageResult<ArticleDTO> searchArticles(String keyword, Integer pageNum, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.DESC, "publishDate"));
        Page<Article> page = articleRepository.findByTitleContaining(keyword, pageable);
        return PageResult.fromPage(page, ArticleDTO::fromEntityForList);
    }

    @Override
    @Transactional
    public void incrementReadCount(Long id) {
        Article article = articleRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("文章不存在"));
        
        // 增加阅读量
        article.setReadCount(article.getReadCount() + 1);
        articleRepository.save(article);
    }
}
